import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:environmental_les_app/common/style/colours.dart';

import 'bottom_screen_dialog.dart';
import 'industry_selection.dart';

/// 可复用的顶部筛选条
///
/// 这个组件不再直接访问页面 controller，而是通过回调和函数参数与上层交互：
/// - [filterData]: 筛选项配置
/// - [selectedFilters]: 当前已选项（传给弹窗作为初始值）
/// - [getSelectedSummary]: 根据 prop 返回摘要 Map { 'label': String? , 'count': int }
/// - [hasSelection]: 根据 prop 返回是否有选中
/// - [onUpdateSelection]: 弹窗确认后回调选中结果（可能为 null，表示清空）
class TopScreenWidget extends StatefulWidget {
  final List<Map<String, dynamic>> filterData;
  final Map<String, List<String>>? initialSelected;
  final void Function(Map<String, List<String>>? selected) onSelectionChanged;
  final EdgeInsets? padding;
  final EdgeInsets? margin;
  final BoxDecoration? decoration;

  const TopScreenWidget({
    super.key,
    required this.filterData,
    this.initialSelected,
    required this.onSelectionChanged,
    this.padding,
    this.margin,
    this.decoration,
  });

  @override
  State<TopScreenWidget> createState() => _TopScreenWidgetState();
}

class _TopScreenWidgetState extends State<TopScreenWidget> {
  late Map<String, List<String>> _selectedFilters;

  @override
  void initState() {
    super.initState();
    // 深拷贝初始选中，防止和外部引用共享同一对象
    _selectedFilters = {};
    if (widget.initialSelected != null) {
      widget.initialSelected!.forEach((k, v) {
        _selectedFilters[k] = List<String>.from(v);
      });
    } else {
      for (final item in widget.filterData) {
        _selectedFilters[item['prop'] as String] = [];
      }
    }
  }

  Map<String, dynamic> _getSelectedSummary(String prop) {
    final sel = _selectedFilters[prop] ?? [];
    if (sel.isEmpty) return {'label': null, 'count': 0};

    final item = widget.filterData
        .firstWhere((e) => e['prop'] == prop, orElse: () => {});
    if (item.isEmpty) return {'label': null, 'count': sel.length};

    final List opts = item['filter'] as List;
    String? firstLabel;
    for (final v in opts) {
      if (v['value'].toString() == sel.first) {
        firstLabel = v['name'] as String;
        break;
      }
    }
    return {'label': firstLabel, 'count': sel.length};
  }

  bool _hasSelection(String prop) {
    return (_selectedFilters[prop]?.isNotEmpty ?? false);
  }

  void _updateSelectionFromResult(Map<String, dynamic>? result) {
    if (result == null) {
      for (final item in widget.filterData) {
        _selectedFilters[item['prop'] as String] = [];
      }
    } else {
      for (final item in widget.filterData) {
        final prop = item['prop'] as String;
        final val = result[prop];
        if (val is List) {
          _selectedFilters[prop] = val.map((e) => e.toString()).toList();
        } else if (val == null) {
          _selectedFilters[prop] = [];
        } else {
          _selectedFilters[prop] = [val.toString()];
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        hGap15,
        ...widget.filterData.map((e) => Expanded(child: optionWidget(e))),
      ],
    );
  }

  // 选项widget
  Widget optionWidget(Map<String, dynamic> e) {
    return InkWell(
      onTap: () {
        // 筛选所属行业 特殊处理
        if (e['title'] == '所属行业') {
          Get.to(const IndustrySelectionWidget());
          return;
        }
        Get.bottomSheet(BottomScreenDialog(
                multiSelect: true,
                filterData: widget.filterData,
                initialSelected: _selectedFilters))
            .then((value) {
          logger.d("筛选结果: $value");
          // 更新内部状态并回调外部（回传为简化后的选中 Map）
          setState(() {
            _updateSelectionFromResult(value as Map<String, dynamic>?);
          });
          // 深拷贝并将 currently selected 转为 Map<String, List<String>>
          final Map<String, List<String>> out = {};
          _selectedFilters.forEach((k, v) {
            out[k] = List<String>.from(v);
          });
          widget.onSelectionChanged(out);
        });
      },
      child: Container(
        padding: widget.padding,
        margin: widget.margin,
        decoration: widget.decoration,
        child: Row(
          children: [
            Builder(builder: (_) {
              final summary = _getSelectedSummary(e['prop']);
              final label = summary['label'] as String?;
              final titleText =
                  (label != null && summary['count'] > 0) ? label : e['title'];
              return Expanded(
                child: Text(titleText,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: _hasSelection(e['prop'])
                            ? Colours.appMain
                            : Colours.text254)),
              );
            }),
            Builder(builder: (_) {
              final summary = _getSelectedSummary(e['prop']);
              final count = summary['count'] as int;
              return Text(count > 0 ? '($count)' : '',
                  style: TextStyle(
                      color: _hasSelection(e['prop'])
                          ? Colours.appMain
                          : Colours.text254));
            }),
            hGap1,
            Icon(
              Icons.arrow_drop_down,
              size: 20,
              color:
                  _hasSelection(e['prop']) ? Colours.appMain : Colours.text969,
            )
          ],
        ),
      ),
    );
  }
}
